#include "updatedialog.h"
#include "updatemanager.h"
#include "configmanager.h"
#include <QVBoxLayout>
#include <QHBoxLayout>
#include <QGridLayout>
#include <QLabel>
#include <QPushButton>
#include <QProgressBar>
#include <QScrollArea>
#include <QApplication>
#include <QDesktopServices>
#include <QUrl>
#include <QDebug>


UpdateDialog::UpdateDialog(const VersionManager::UpdateInfo& updateInfo, QWidget* parent)
    : QDialog(parent)
    , m_updateInfo(updateInfo)
    , m_result(Later)
    , m_isDownloading(false)
    , m_downloadComplete(false)
    , m_hashVerified(false)
    , m_downloadSpeed(0)
    , m_lastSpeedCheck(0)
    , m_lastDownloadedBytes(0)
    , m_progressTimer(new QTimer(this))
    , m_speedTimer(new QTimer(this))
{

    setupUI();
    setupStyles();

    // 连接定时器
    connect(m_progressTimer, &QTimer::timeout, this, &UpdateDialog::updateProgressDisplay);
    connect(m_speedTimer, &QTimer::timeout, this, [this]() {
        if (m_isDownloading) {
            qint64 currentTime = QDateTime::currentMSecsSinceEpoch();
            if (m_lastSpeedCheck > 0) {
                qint64 timeDiff = currentTime - m_lastSpeedCheck;
                if (timeDiff > 1000) {
                    m_downloadSpeed = m_lastDownloadedBytes * 1000 / timeDiff;
                    m_speedLabel->setText(tr("下载速度：%1").arg(formatSpeed(m_downloadSpeed)));
                    m_lastSpeedCheck = currentTime;
                    m_lastDownloadedBytes = 0;
                }
            }
        }
    });

    setModal(true);
    setFixedSize(DIALOG_WIDTH, DIALOG_HEIGHT);
}

UpdateDialog::~UpdateDialog()
{
}

void UpdateDialog::setupUI()
{
    m_mainLayout = new QVBoxLayout(this);
    m_mainLayout->setSpacing(12);
    m_mainLayout->setContentsMargins(40, 30, 40, 30);

    // 标题
    m_titleLabel = new QLabel(this);
    if (m_updateInfo.forceUpdate) {
        m_titleLabel->setText(tr("重要更新通知"));
        m_titleLabel->setStyleSheet("font-size: 18pt; font-weight: 600; color: #1d1d1f; margin-bottom: 8px;");
    } else {
        m_titleLabel->setText(tr("发现新版本"));
        m_titleLabel->setStyleSheet("font-size: 18pt; font-weight: 600; color: #1d1d1f; margin-bottom: 8px;");
    }

    // 版本信息
    m_versionInfoLabel = new QLabel(this);
    m_versionInfoLabel->setText(tr("LimeReader %1 现已可用！")
                              .arg(m_updateInfo.latestVersion.toString()));
    m_versionInfoLabel->setStyleSheet("font-size: 15pt; font-weight: 500; color: #1d1d1f; margin-bottom: 16px;");

    // 当前版本信息
    QLabel* currentVersionLabel = new QLabel(tr("当前版本：%1").arg(ConfigManager::getCurrentVersion()));
    currentVersionLabel->setStyleSheet("font-size: 13pt; color: #48484a; margin-bottom: 4px;");

    // 文件大小
    QString sizeText = m_updateInfo.updateSize;
    if (sizeText.isEmpty()) {
        sizeText = tr("计算中...");
    }
    m_sizeLabel = new QLabel(tr("文件大小：%1").arg(sizeText));
    m_sizeLabel->setStyleSheet("font-size: 13pt; color: #48484a; margin-bottom: 4px;");

    // MD5校验值
    QString md5Text = m_updateInfo.checksumMD5;
    if (md5Text.isEmpty()) {
        md5Text = tr("无校验信息");
    } else if (md5Text.length() > 16) {
        // 显示前8位和后8位，中间用...代替
        md5Text = md5Text.left(8) + "..." + md5Text.right(8);
    }
    m_md5Label = new QLabel(tr("MD5校验：%1").arg(md5Text));
    m_md5Label->setStyleSheet("font-size: 13pt; color: #48484a; margin-bottom: 16px; font-family: monospace;");

    // 更新日志
    QLabel* changelogTitleLabel = new QLabel(tr("更新内容："));
    changelogTitleLabel->setStyleSheet("font-size: 13pt; font-weight: 500; color: #1d1d1f; margin-bottom: 8px;");

    m_changelogLabel = new QLabel(this);
    m_changelogLabel->setWordWrap(true);
    m_changelogLabel->setMinimumHeight(100);
    m_changelogLabel->setMaximumHeight(120);
    m_changelogLabel->setAlignment(Qt::AlignTop | Qt::AlignLeft);
    m_changelogLabel->setStyleSheet(
        "font-size: 13pt; color: #48484a; background-color: #f5f5f5; "
        "border-radius: 8px; padding: 12px; border: 1px solid #e5e5e7;"
    );

    // 设置更新日志
    QString changelog = m_updateInfo.updateLog;
    if (changelog.isEmpty()) {
        changelog = tr("• 性能优化\n• 稳定性提升\n• 用户体验改进");
    } else {
        // 处理长文本
        if (changelog.length() > 300) {
            changelog = changelog.left(300) + "...";
        }
        // 确保每行不超过一定长度
        QStringList lines = changelog.split('\n');
        for (int i = 0; i < lines.size(); ++i) {
            if (lines[i].length() > 50) {
                lines[i] = lines[i].left(47) + "...";
            }
        }
        changelog = lines.join('\n');
    }
    m_changelogLabel->setText(changelog);

    // 进度条区域（初始隐藏）
    m_progressLayout = new QHBoxLayout();
    m_progressLayout->setContentsMargins(0, 16, 0, 8);

    m_progressBar = new QProgressBar(this);
    m_progressBar->setFixedHeight(PROGRESS_HEIGHT);
    m_progressBar->setTextVisible(false);
    m_progressBar->setStyleSheet(
        "QProgressBar {"
        "  border: none;"
        "  border-radius: 4px;"
        "  background-color: #f5f5f5;"
        "}"
        "QProgressBar::chunk {"
        "  border-radius: 4px;"
        "  background-color: #007aff;"
        "}"
    );

    QLabel* progressPercentLabel = new QLabel("0%");
    progressPercentLabel->setStyleSheet("font-size: 13pt; color: #48484a;");

    m_progressLayout->addWidget(m_progressBar, 1);
    m_progressLayout->addWidget(progressPercentLabel);

    // 状态区域
    m_statusLayout = new QHBoxLayout();
    m_statusLayout->setContentsMargins(0, 0, 0, 16);

    m_statusLabel = new QLabel(tr("准备下载..."));
    m_statusLabel->setStyleSheet("font-size: 13pt; color: #48484a;");

    m_speedLabel = new QLabel();
    m_speedLabel->setStyleSheet("font-size: 13pt; color: #8e8e93;");
    m_speedLabel->hide();

    m_statusLayout->addWidget(m_statusLabel);
    m_statusLayout->addStretch();
    m_statusLayout->addWidget(m_speedLabel);

    // 文件路径（下载完成时显示）
    m_filePathLabel = new QLabel();
    m_filePathLabel->setWordWrap(true);
    m_filePathLabel->hide();
    m_filePathLabel->setStyleSheet("font-size: 12pt; color: #8e8e93;");

    // 按钮区域 - 使用固定布局避免动态修改问题
    m_buttonLayout = new QHBoxLayout();
    m_buttonLayout->setSpacing(12);
    m_buttonLayout->setContentsMargins(0, 8, 0, 0);

    // 创建所有按钮
    m_updateButton = new QPushButton(tr("立即更新"));
    m_updateButton->setFixedSize(BUTTON_WIDTH, BUTTON_HEIGHT);
    m_updateButton->setObjectName("primaryButton");

    m_laterButton = new QPushButton(tr("稍后提醒"));
    m_laterButton->setFixedSize(BUTTON_WIDTH, BUTTON_HEIGHT);

    m_skipButton = new QPushButton(tr("跳过此版本"));
    m_skipButton->setFixedSize(BUTTON_WIDTH, BUTTON_HEIGHT);

    m_openFolderButton = new QPushButton(tr("打开文件夹"));
    m_openFolderButton->setFixedSize(BUTTON_WIDTH, BUTTON_HEIGHT);

    m_closeButton = new QPushButton(tr("关闭"));
    m_closeButton->setFixedSize(BUTTON_WIDTH, BUTTON_HEIGHT);

    // 居中布局：左右各一个伸缩空间，按钮组居中，默认按钮在最右
    m_buttonLayout->addStretch();                   // 左侧伸缩空间
    m_buttonLayout->addWidget(m_skipButton);        // 跳过版本按钮
    m_buttonLayout->addWidget(m_laterButton);       // 稍后提醒按钮
    m_buttonLayout->addWidget(m_updateButton);      // 重新下载按钮
    m_buttonLayout->addWidget(m_openFolderButton);  // 打开文件夹按钮
    m_buttonLayout->addWidget(m_closeButton);       // 关闭/安装更新按钮（默认按钮）
    m_buttonLayout->addStretch();                   // 右侧伸缩空间

    // 初始状态：根据是否强制更新显示不同按钮
    if (m_updateInfo.forceUpdate) {
        // 强制更新：只显示更新按钮
        m_updateButton->show();
        m_updateButton->setDefault(true);  // 设为默认按钮
        m_skipButton->hide();
        m_laterButton->hide();
        m_openFolderButton->hide();
        m_closeButton->hide();
    } else {
        // 正常更新：显示跳过、稍后、立即更新
        m_skipButton->show();
        m_laterButton->show();
        m_updateButton->show();
        m_updateButton->setDefault(true);  // 设为默认按钮
        m_openFolderButton->hide();
        m_closeButton->hide();
    }

    // 添加到主布局
    m_mainLayout->addWidget(m_titleLabel);
    m_mainLayout->addWidget(m_versionInfoLabel);
    m_mainLayout->addWidget(currentVersionLabel);
    m_mainLayout->addWidget(m_sizeLabel);
    m_mainLayout->addWidget(m_md5Label);
    m_mainLayout->addWidget(changelogTitleLabel);
    m_mainLayout->addWidget(m_changelogLabel);
    m_mainLayout->addLayout(m_progressLayout);
    m_mainLayout->addLayout(m_statusLayout);
    m_mainLayout->addWidget(m_filePathLabel);
    m_mainLayout->addLayout(m_buttonLayout);

    // 初始状态
    m_progressLayout->parentWidget()->hide();
    m_filePathLabel->hide();

    // 连接信号
    connect(m_updateButton, &QPushButton::clicked, this, &UpdateDialog::onUpdateClicked);
    connect(m_laterButton, &QPushButton::clicked, this, &UpdateDialog::onLaterClicked);
    connect(m_skipButton, &QPushButton::clicked, this, &UpdateDialog::onSkipClicked);
    connect(m_openFolderButton, &QPushButton::clicked, this, &UpdateDialog::openDownloadFolder);
    connect(m_retryButton, &QPushButton::clicked, this, &UpdateDialog::onUpdateClicked);
    connect(m_closeButton, &QPushButton::clicked, this, &UpdateDialog::onCloseClicked);
}

void UpdateDialog::setupStyles()
{
    // 使用与登录对话框一致的统一按钮样式
    setStyleSheet(R"(
        QDialog {
            background-color: #F5F5F5;
        }

        QPushButton {
            background-color: #f0f0f0;
            color: #333;
            border: 1px solid #ccc;
            border-radius: 4px;
            padding: 6px 12px;
            font-size: 11pt;
            text-align: center;
        }

        QPushButton:hover {
            background-color: #e0e0e0;
            border-color: #999;
        }

        QPushButton:pressed {
            background-color: #d0d0d0;
        }

        QPushButton:disabled {
            background-color: #F7F9FA;
            color: #BDC3C7;
            border-color: #E5E8E8;
        }

        #primaryButton {
            background-color: #007aff;
            color: white;
            border: 1px solid #007aff;
        }

        #primaryButton:hover {
            background-color: #0056cc;
            border-color: #0056cc;
        }

        #primaryButton:pressed {
            background-color: #004999;
            border-color: #004999;
        }
    )");
}

void UpdateDialog::onUpdateClicked()
{

    if (m_isDownloading) {
        // 暂停下载
        emit requestPauseDownload();
    } else if (m_downloadComplete && !m_hashVerified) {
        // 下载完成但校验失败 - 重新下载
        // 重置状态
        m_downloadComplete = false;
        m_hashVerified = false;
        m_downloadFilePath.clear();
        // 开始重新下载
        m_result = Update;
        updateDownloadMode();
        emit requestStartDownload();
    } else if (m_downloadComplete && m_hashVerified) {
        // 下载完成且校验通过 - 重新安装
        QDesktopServices::openUrl(QUrl::fromLocalFile(m_downloadFilePath));
    } else {
        // 开始下载

        m_result = Update;
        updateDownloadMode();

        emit requestStartDownload();
    }
}

void UpdateDialog::onLaterClicked()
{
    m_result = Later;
    reject();
}

void UpdateDialog::onSkipClicked()
{
    m_result = Skip;
    // 记录跳过的版本
    ConfigManager::setSkippedVersion(m_updateInfo.latestVersion.toString());
    reject();
}

void UpdateDialog::onCloseClicked()
{
    // 根据按钮文本判断是关闭还是安装更新
    if (m_closeButton->text() == tr("安装更新")) {
        // 执行安装更新操作
        if (!m_downloadFilePath.isEmpty()) {
            // 打开下载的文件进行安装
            QDesktopServices::openUrl(QUrl::fromLocalFile(m_downloadFilePath));
        }
        m_result = Update;
        accept();  // 成功完成
    } else {
        // 普通关闭
        reject();
    }
}

void UpdateDialog::onDownloadProgress(int progress, qint64 received, qint64 total)
{
    if (!m_isDownloading) {
        m_isDownloading = true;
        updateDownloadMode();
        m_progressTimer->start(100); // 每100ms更新一次显示
        m_speedTimer->start(1000); // 每秒更新一次速度
        m_lastSpeedCheck = QDateTime::currentMSecsSinceEpoch();
        m_lastDownloadedBytes = 0;

        // 设置文件大小（第一次获取到total时）
        if (total > 0) {
            setDownloadFileSize(total);
        }
    }

    m_lastDownloadedBytes += (received - (total - received));

    // 更新进度条
    m_progressBar->setValue(progress);

    // 更新百分比标签
    QWidget* percentWidget = m_progressLayout->itemAt(1)->widget();
    if (QLabel* percentLabel = qobject_cast<QLabel*>(percentWidget)) {
        percentLabel->setText(QString("%1%").arg(progress));
    }

    // 更新状态
    m_statusLabel->setText(tr("正在下载..."));
}

void UpdateDialog::onDownloadFinished(const QString& filePath)
{
    m_downloadComplete = true;
    m_isDownloading = false;
    m_downloadFilePath = filePath;

    // 执行哈希校验
    m_hashVerified = verifyFileHash(filePath, m_updateInfo.checksumMD5);

    showCompleteMode();

    // 停止定时器
    m_progressTimer->stop();
    m_speedTimer->stop();
}

void UpdateDialog::onDownloadError(const QString& error)
{
    m_isDownloading = false;
    m_lastError = error;
    showErrorMode(error);

    // 停止定时器
    m_progressTimer->stop();
    m_speedTimer->stop();
}

void UpdateDialog::updateProgressDisplay()
{
    if (m_isDownloading) {
        // 更新速度显示
        if (m_lastSpeedCheck > 0) {
            qint64 currentTime = QDateTime::currentMSecsSinceEpoch();
            qint64 timeDiff = currentTime - m_lastSpeedCheck;
            if (timeDiff > 100) {
                qint64 speed = m_lastDownloadedBytes * 1000 / timeDiff;
                m_speedLabel->setText(tr("下载速度：%1").arg(formatSpeed(speed)));
                m_lastSpeedCheck = currentTime;
                m_lastDownloadedBytes = 0;
            }
        }
    }
}

void UpdateDialog::updateDownloadMode()
{
    // 显示进度区域
    m_progressLayout->parentWidget()->show();
    m_speedLabel->show();

    // 更新按钮文本和显示状态
    m_updateButton->setText(tr("暂停"));
    m_updateButton->show();

    // 设置下载中的按钮显示状态
    if (m_updateInfo.forceUpdate) {
        // 强制更新：只显示暂停按钮
        m_skipButton->hide();
        m_laterButton->hide();
        m_openFolderButton->hide();
        m_closeButton->hide();
    } else {
        // 正常更新：显示暂停和关闭按钮
        m_skipButton->hide();
        m_laterButton->hide();
        m_openFolderButton->hide();
        m_closeButton->show();
    }
}

void UpdateDialog::showProgressMode()
{
    m_progressLayout->parentWidget()->show();
    m_statusLabel->setText(tr("正在下载..."));
}

void UpdateDialog::showCompleteMode()
{
    // 隐藏进度相关
    m_speedLabel->hide();

    // 根据哈希校验结果设置状态
    if (m_hashVerified) {
        m_statusLabel->setText(tr("下载完成，校验通过！"));
        // 更新MD5标签显示校验通过
        m_md5Label->setText(tr("MD5校验：通过 ✓"));
        m_md5Label->setStyleSheet("font-size: 13pt; color: #28a745; margin-bottom: 16px; font-family: monospace;");
    } else {
        m_statusLabel->setText(tr("下载完成，但校验失败！"));
        // 更新MD5标签显示校验失败
        m_md5Label->setText(tr("MD5校验：失败 ✗"));
        m_md5Label->setStyleSheet("font-size: 13pt; color: #dc3545; margin-bottom: 16px; font-family: monospace;");
    }

    // 显示文件路径
    m_filePathLabel->setText(tr("文件位置：%1").arg(m_downloadFilePath));
    m_filePathLabel->show();

    // 根据哈希校验结果设置按钮显示状态
    if (m_hashVerified) {
        // 校验通过：显示[打开文件夹] [安装更新]
        m_updateButton->hide();
        m_skipButton->hide();
        m_laterButton->hide();
        m_openFolderButton->show();
        m_closeButton->show();
        m_closeButton->setText(tr("安装更新"));
        m_closeButton->setObjectName("primaryButton");
    } else {
        // 校验失败：显示[重新下载] [打开文件夹] [关闭]
        m_updateButton->show();
        m_updateButton->setText(tr("重新下载"));
        m_skipButton->hide();
        m_laterButton->hide();
        m_openFolderButton->show();
        m_closeButton->show();
        m_closeButton->setText(tr("关闭"));
        m_closeButton->setObjectName("");
    }
}

void UpdateDialog::showErrorMode(const QString& error)
{
    m_statusLabel->setText(tr("下载失败：%1").arg(error));

    // 设置错误状态的按钮显示：[重试] [关闭]
    m_updateButton->setText(tr("重试"));
    m_updateButton->show();
    m_skipButton->hide();
    m_laterButton->hide();
    m_openFolderButton->hide();
    m_closeButton->show();
}

void UpdateDialog::openDownloadFolder()
{
    QFileInfo fileInfo(m_downloadFilePath);
    QDesktopServices::openUrl(QUrl::fromLocalFile(fileInfo.absolutePath()));
}

QString UpdateDialog::formatFileSize(qint64 bytes) const
{
    if (bytes < 1024) {
        return QString("%1 B").arg(bytes);
    } else if (bytes < 1024 * 1024) {
        return QString("%1 KB").arg(bytes / 1024.0, 0, 'f', 1);
    } else if (bytes < 1024 * 1024 * 1024) {
        return QString("%1 MB").arg(bytes / (1024.0 * 1024.0), 0, 'f', 1);
    } else {
        return QString("%1 GB").arg(bytes / (1024.0 * 1024.0 * 1024.0), 0, 'f', 1);
    }
}

QString UpdateDialog::formatSpeed(qint64 bytesPerSecond) const
{
    return formatFileSize(bytesPerSecond) + "/s";
}

void UpdateDialog::setDownloadFileSize(qint64 bytes)
{
    m_sizeLabel->setText(tr("文件大小：%1").arg(formatFileSize(bytes)));
}

bool UpdateDialog::verifyFileHash(const QString& filePath, const QString& expectedHash) const
{
    if (expectedHash.isEmpty()) {
        return true; // 没有哈希值时跳过校验
    }

    QFile file(filePath);
    if (!file.open(QIODevice::ReadOnly)) {
        return false;
    }

    QCryptographicHash hash(QCryptographicHash::Md5);
    while (!file.atEnd()) {
        QByteArray data = file.read(8192);
        hash.addData(data);
    }

    QString actualHash = hash.result().toHex();

    bool isValid = (actualHash.toLower() == expectedHash.toLower());

    return isValid;
}